import unittest, sys
import picklewrapper as pwr

FNAME = 'test.dat'

class Foo(object):
    def __init__(self, value):
        self.value = value

class FooBar(object):
    def __init__(self, foo_val, bar_val):
        self.foo = Foo(foo_val)
        self.bar = bar_val


class BasicTests(unittest.TestCase):
    def test_s1(self):
        x = 1234
        yy = 99
        pwr.save(FNAME, 'x')
        del x
        d = pwr.load(FNAME)
        x = d['x']
        self.assertTrue(x == 1234)

    def test_s2(self):
        x = 100
        y = 1000
        z = 'ten-thousand'
        pwr.save(FNAME, 'x','y','z')
        x = None; y=None; z=None;
        d = pwr.load(FNAME)
        x = d['x']; y = d['y']; z = d['z'];
        self.assertTrue(x == 100)
        self.assertTrue(y == 1000)
        self.assertTrue(z == 'ten-thousand')

    def test_s3(self):
        x = 11
        y = 22
        z = 'one'
        w = Foo(44)
        pwr.save(FNAME, 'x','y','z','w')
        x = None; y=None; z=None; w=None;
        d = pwr.load(FNAME)
        x = d['x']; y = d['y']; z = d['z']; w = d['w'];
        self.assertTrue(x == 11)
        self.assertTrue(y == 22)
        self.assertTrue(z == 'one')
        self.assertTrue(type(w) is Foo)
        self.assertTrue(w.value == 44)

    def test_s4(self):
        x = 1
        y = 2
        z = 'three'
        w = Foo(4)
        u = FooBar(5,6)
        pwr.save(FNAME, 'x','y','z','w','u')
        x = None; y=None; z=None; w=None; u=None
        d = pwr.load(FNAME)
        x = d['x']; y = d['y']; z = d['z']; w = d['w']; u = d['u'];
        self.assertTrue(x == 1)
        self.assertTrue(y == 2)
        self.assertTrue(z == 'three')
        self.assertTrue(w.value==4)
        self.assertTrue( (type(w) is Foo) and (type(u) is FooBar) )
        self.assertTrue(u.foo.value==5 and u.bar==6)


class ErrorTests(unittest.TestCase):
    
    def test_e1(self):
        """
        tests invalid *args parameters to save
        """
        isGood = False
        x = 100
        try:
            pwr.save(FNAME, x)
        except pwr.InvalidArgError:
            isGood = True
        self.assertTrue(isGood)

    def test_e2(self):
        """
        tests invalid fname parameters to save
        """
        isGood = False
        x = 100
        try:
            pwr.save(123, 'x')
        except pwr.InvalidArgError:
            isGood = True
        self.assertTrue(isGood)

    def test_e3(self):
        """
        tests non-existant variable in caller
        """
        isGood = False
        x = 1
        y = 2
        try:
            pwr.save(FNAME, 'x', 'y', 'z')
        except pwr.VarDoesNotExist as e:
            self.assertTrue(e.var_name == 'z')
            isGood = True
        self.assertTrue(isGood)

 
if __name__ == '__main__':
    unittest.main()
